import router from "@/router";
import { defineStore } from "pinia";
import { ref } from "vue";
import pinia, { useKeepAliveStore } from "@/stores/index";
import { getlocalStorage, removeItem, setlocalStorage } from "@/utils/localStorage";
import { Keys } from "@/utils/localStore_key";


 export const useTabsStore=defineStore('tabs',()=>{
     const KeepAliveStore=useKeepAliveStore(pinia)
      const tabsMenuList=ref<any[]>(getlocalStorage(Keys.TABSLIST) || [])
      // 添加
      const addTabs= async (tabItem:any)=>{
        // console.log(tabItem);
        // console.log(tabsMenuList.value.every((item:any)=>item.path !== tabItem.path));
         if(tabsMenuList.value.every((item:any)=>item.path !== tabItem.path)){
             tabsMenuList.value.push(tabItem)
             setTabslocalStorage(tabsMenuList.value)
         }
         if(!KeepAliveStore.keepNameLsit.includes(tabItem.name) && tabItem.keepAlive){
              console.log(tabItem.name,tabItem.keepAlive);
              KeepAliveStore.addKeepAliveName(tabItem.name)
         }
      }
      // 删除
      const removeTabs=(tabpath:string,isCurrent:boolean)=>{
        // console.log(tabpath,isCurrent);
        if(isCurrent){
          tabsMenuList.value.forEach((item,index)=>{
              if(item.path !== tabpath) return
              const nextTab=tabsMenuList.value[index + 1] || tabsMenuList.value[index - 1]
              if(!nextTab) return
              router.push(nextTab.path)
          })
        }
       const tabItem=tabsMenuList.value.find((item)=>item.path == tabpath)
       KeepAliveStore.removeKeepAliveName(tabItem.path)
       tabsMenuList.value = tabsMenuList.value.filter(item => item.path !== tabpath);
       setTabslocalStorage(tabsMenuList.value)
      }

      // 重新登录设为空
      const  setTabs=async(tabsMenuLists:any) =>{
        tabsMenuList.value = tabsMenuLists;
      }

      const setTabslocalStorage=(value:any)=>{
          setlocalStorage(Keys.TABSLIST,value as any)
      }
      return {tabsMenuList , addTabs , removeTabs , setTabs , setTabslocalStorage}
 })
